package com.tsd.job;

import cn.hutool.db.Entity;
import com.tsd.common.dao.CommonFileMapper;
import com.tsd.common.entity.CommonFile;
import com.tsd.core.annotation.TaskJob;
import com.tsd.core.annotation.TaskJobMethod;
import com.tsd.core.config.Config;
import com.tsd.core.constants.ConfigKeyConstants;
import com.tsd.core.constants.Constants;
import com.tsd.core.datasource.DataSourceContextHolder;
import com.tsd.core.job.JobBaseClass;
import com.tsd.core.job.JobUtils;
import com.tsd.core.utils.ExceptionUtil;
import com.tsd.core.utils.FileUtil;
import com.tsd.core.utils.HlpUtils;
import com.tsd.core.utils.ListUtil;
import com.tsd.job.dao.SysTaskJobMapper;
import com.tsd.job.entity.SysTaskJobExt;
import com.tsd.system.dao.SqlSelectMapper;
import com.tsd.system.dao.SysAccountSetMapper;
import com.tsd.system.entity.SysAccountSetExt;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 通过数据库配置定时任务的使用方法
 * 编写SpringBean,建议继承JobBaseClass，
 * 方法没有参数，在方法内需要先获取账套，然后再逐个账套进行处理，执行日志写到主账套的任务执行日志中
 * 建议采用如下编写方式：
 * public void startJob() {
 * super.fetchAccountSet(sysAccountSetService,"资产管理-合同",new CallBack(){
 *
 * @Override public void dealWith(SysAccountSetExt sysAccountSetExt) {
 * procOneAccountSet(sysAccountSetExt);
 * }
 * });
 * }
 * 然后主要编写procOneAccountSet(sysAccountSetExt)的逻辑
 * @ClassName: QuartzJob
 * @Description: quartz定时任务
 * @Author: Luoyc
 * @Date: 2020/4/23 11:13
 * @Version: 1.0
 */
@TaskJob(name = "quartz定时任务")
public class QuartzJob extends JobBaseClass {

    private static final Logger LOGGER = LoggerFactory.getLogger("quartzLogger");

    @Resource
    private CommonFileMapper commonFileMapper;
    @Resource
    SqlSelectMapper sqlSelectMapper;
    @Resource
    SysAccountSetMapper sysAccountSetMapper;
    @Resource
    SysTaskJobMapper sysTaskJobMapper;

    @TaskJobMethod(name = "测试Quartz配置")
    public void check(SysTaskJobExt jobExt) {
        LOGGER.info("测试Quartz配置");
    }

    @TaskJobMethod(name = "检查账套是否已经过期")
    public void checkAccountSetExpired(SysTaskJobExt jobExt) {
        LOGGER.info("开始：检查账套是否已经过期");
        SysAccountSetExt t = new SysAccountSetExt();
        int qty = 0;
        int code = 0;
        Entity logEntity = new Entity();
        logEntity.put("job_object_name", QuartzJob.class.getName());
        logEntity.put("job_method_name", "checkAccountSetExpired");
        logEntity.put("update_date", new Date());
        logEntity.put("owner_sid", null);
        try {
            t.setExpired_date(HlpUtils.getTheDate(new Date()));
            qty = sysAccountSetMapper.updateExpired(t);
            sysAccountSetMapper.update2Free4Expired();
            logEntity.put("exec_code", code);
            logEntity.put("ext0", BigDecimal.valueOf(qty));
        }catch (Exception e){
            jobExt.setLast_error(e.getMessage());
            sysTaskJobMapper.updateByPrimaryKeySelective(jobExt);
            code = -1;
            logEntity.put("exec_code", code);
            logEntity.put("ext0", BigDecimal.valueOf(qty));
            logEntity.put("exec_msg", e.getMessage());
            logEntity.put("exec_trace", ExceptionUtil.getStackTraceFromException(e));
        }finally {
            JobUtils.saveJobExecLog(DataSourceContextHolder.getMasterDataSource(), logEntity);
        }
    }
    @TaskJobMethod(name = "清理临时目录方法")
    public void clearTemp(SysTaskJobExt jobExt) {
        LOGGER.info("执行清理临时目录方法：clearTemp");
        try {
            // 上传的根目录
            String rootPath = Config.getParameterValue(ConfigKeyConstants.UPLOAD_ROOT_PATH);
            File rootAndMidPathFile = new File(rootPath + File.separator + "temp");
            FileUtil.deleteDir(rootAndMidPathFile);
            if (!rootAndMidPathFile.exists()) {
                rootAndMidPathFile.mkdirs();
            }
            List<CommonFile> delList = new ArrayList<>();
            List<CommonFile> list = commonFileMapper.selectByOwnerSid("export");
            if (!HlpUtils.isEmptyList(list)) {
                delList.addAll(list);
            }
            List<CommonFile> list2 = commonFileMapper.selectByBizType("import");
            if (!HlpUtils.isEmptyList(list2)) {
                delList.addAll(list2);
            }
            List<String> idList = ListUtil.map(delList, CommonFile::getSid);
            if (!HlpUtils.isEmptyList(idList)) {
                commonFileMapper.selectBySidList(idList);
            }
        } catch (Exception e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        }
    }

    /**
     * 在某个账套上建日志表
     */
    public void createTableLogInfo4AccountSet(String sid) {
        String accountSetSid = sid + Constants.DATABASE_SUFFIX_FOR_LOG;
        try {
            if (!HlpUtils.isEmpty(accountSetSid)) {
                DataSourceContextHolder.setDataSourceType(accountSetSid);
            } else {
                DataSourceContextHolder.setDataSourceType(null);
            }
            //当月日志表
            Date now = new Date();
            String suff = HlpUtils.date2String(now, "yyyyMM");
            String sql = "CREATE TABLE IF NOT EXISTS sys_log_info_" + suff + "  LIKE sys_log_info";
            sqlSelectMapper.insert(sql);

            //下月日志表
            Date nextMonth = HlpUtils.getNextDateByMonth(now, 1);
            suff = HlpUtils.date2String(nextMonth, "yyyyMM");
            sql = "CREATE TABLE IF NOT EXISTS sys_log_info_" + suff + "   LIKE sys_log_info";
            sqlSelectMapper.insert(sql);
        } catch (Exception e) {
            LOGGER.error(ExceptionUtil.getStackTraceFromException(e));
        }
    }
}
